package com.yunchao.maintenance.presentation.screen

import android.Manifest
import android.os.Build
import android.os.Bundle
import android.view.KeyEvent
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import android.widget.Toast.LENGTH_LONG
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import by.kirich1409.viewbindingdelegate.viewBinding
import com.permissionx.guolindev.PermissionX
import com.seuic.scankey.IKeyEventCallback
import com.seuic.scankey.ScanKeyService
import com.xuexiang.xui.utils.KeyboardUtils
import com.xuexiang.xui.utils.WidgetUtils
import com.yunchao.feature.base.presentation.activity.BaseActivity
import com.yunchao.feature.base.presentation.ext.hideLoadingDialog
import com.yunchao.feature.base.presentation.ext.setDebouncedClickListener
import com.yunchao.feature.base.presentation.ext.showLoadingDialog
import com.yunchao.feature.base.presentation.ext.showSingleChoiceDialog
import com.yunchao.feature.base.presentation.ext.showTipDialog
import com.yunchao.feature.base.presentation.ext.toast
import com.yunchao.maintenance.R
import com.yunchao.maintenance.databinding.ActivityMainBinding
import kotlinx.coroutines.launch
import org.koin.android.ext.android.inject
import org.koin.androidx.viewmodel.ext.android.viewModel
import timber.log.Timber
import kotlin.getValue

class MainActivity : BaseActivity(R.layout.activity_main) {

    private val viewModel: MainViewModel by viewModel()
    private val binding: ActivityMainBinding by viewBinding()
    private val scanKeyService: ScanKeyService by inject()
    private val mainAdapter: MainAdapter by lazy { MainAdapter() }

    override fun onCreate(savedInstanceState: Bundle?) {
        setTheme(R.style.Theme_YC_HFED_guangdong_Projects)
        scanKeyService.registerCallback(mCallback, "250")
        super.onCreate(savedInstanceState)
        binding.imageView.setDebouncedClickListener { viewModel.getMaintenanceFileList() }

        binding.mainRecyclerView.apply {
            adapter = mainAdapter
            WidgetUtils.initRecyclerView(this, 0)
        }

        binding.button.setDebouncedClickListener{
            viewModel.saveDataToFile(mainAdapter.items)
        }

        binding.editTextText.setOnEditorActionListener(object : TextView.OnEditorActionListener {
            override fun onEditorAction(
                v: TextView?,
                actionId: Int,
                event: KeyEvent?
            ): Boolean {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    KeyboardUtils.hideSoftInput(v)
                    viewModel.getMaintenanceInfo(binding.editTextText.text.toString())
                    return true
                }
                return false
            }
        })

        val requestList = ArrayList<String>()

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // Android 13 及以上版本使用细粒度媒体权限
            requestList.add(Manifest.permission.READ_MEDIA_IMAGES)
            requestList.add(Manifest.permission.READ_MEDIA_AUDIO)
            requestList.add(Manifest.permission.READ_MEDIA_VIDEO)
        } else {
            // Android 13 以下版本使用旧的外部存储权限
            requestList.add(Manifest.permission.READ_EXTERNAL_STORAGE)
            requestList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
        }

        PermissionX.init(this)
            .permissions(requestList)
            .request { allGranted, _, deniedList ->
                if (allGranted) {
                    // 所有权限都已授予
                    viewModel.openDevice()
                } else {
                    // 有部分权限被拒绝
                    toast("您拒绝了如下权限：$deniedList")
                }
            }




        lifecycleScope.launch { viewModel.uiStateFlow.collect(::render) }
        lifecycleScope.launch { viewModel.uiEffectFlow.collect(::effect) }

    }

    private fun render(state: MainViewModel.UiState) {
        when (state) {
            is MainViewModel.UiState.Content -> {
                if (mainAdapter.items.isEmpty()){
                    state.data?.let {
                        mainAdapter.submitList(mutableListOf(it))
                    }
                }else{
                    state.data?.let {
                        mainAdapter.add(0, it)
                    }
                }
            }

            is MainViewModel.UiState.ListData -> {
                Timber.i("render: ${state.list}")
                if (mainAdapter.items.isEmpty()) {
                    mainAdapter.submitList(state.list.toMutableList())
                } else {
                    mainAdapter.addAll(0, state.list)
                }
            }

            is MainViewModel.UiState.Idle -> Unit

        }
    }

    private fun effect(effect: MainViewModel.UiEffect) {
        when (effect) {
            is MainViewModel.UiEffect.ShowLoading -> showLoadingDialog()
            is MainViewModel.UiEffect.HideLoading -> hideLoadingDialog()
            is MainViewModel.UiEffect.SuccessDialog -> hideLoadingDialog().apply {
                showTipDialog(
                    content = effect.content
                )
            }

            is MainViewModel.UiEffect.ShowToast -> hideLoadingDialog().apply {
                toast(
                    effect.msg,
                    length = LENGTH_LONG
                )
            }

            is MainViewModel.UiEffect.FileList -> showSingleChoiceDialog(
                title = "选择文件",
                items = effect.list.map { it.name },
                selectedIndex = 0
            ) {
                viewModel.handleMaintenanceFile(effect.list[it].name)
            }
        }
    }

    override fun onDestroy() {
        scanKeyService.unregisterCallback(mCallback)
        super.onDestroy()
        viewModel.closeDevice()
    }

    private val mCallback: IKeyEventCallback = object : IKeyEventCallback.Stub() {
        override fun onKeyDown(p0: Int) {
            viewModel.inventoryAll(mainAdapter.items)
        }

        override fun onKeyUp(p0: Int) {
            viewModel.stopInventory()
        }

    }
}